package ltd.followkba.task;

import com.kcbsdk.AFileBase;
import com.kcbsdk.AUserBase;
import com.kcbsdk.MyWorks.AGiftBean;

import java.util.ArrayList;

import java.util.List;
import java.util.Random;

import ltd.advskin.MSKIN;
import ltd.followkba.MAPP;
import ltd.followkba.MDBS;
import ltd.followkba.W;
import main.CApiUtils;
import main.MAPI;

import static ltd.advskin.MSKIN.MLOGE;
import static ltd.advskin.MSKIN.MSTRING;
import static main.MAPI.mMyUtils;

public class WorksQueue {
    public static List<BFileBase>[] mRankQueue;          // 在榜单之中找到的作品队列
    public static List<BFileBase>[] mUserQueue;          // 在评论之中找到的用户队列
    public static List<BFileBase>[] mWorksQueue;         // 找到的作品队列
    public static String[][] mAccount33;
    public static int[] mRankCounter;                     // 榜单上次的计数器
    public static String[] RankName;
    public static String NowName;                      // 在占用中的作品类型
    public static long NowTick;                        // 在占用中的作品时间
    private static boolean isClose;
    private static boolean isPause;
    private static int gApp32Count;
    private static int gNumber;

    public static void MLOG(String text) {
        MSTRING("WorksQueue A " + text);
    }
    public static void setStart(){                                                            // 处理榜单、评论之中的作品队列
        int length = MAPP.mWorksType != null ? MAPP.mWorksType.length : 0;                        ;
        mRankQueue = new List[length];            // 在榜单之中找到的作品队列
        mUserQueue = new List[length];           // 在评论之中找到的用户队列
        mWorksQueue = new List[length];         // 找到的作品队列
        mRankCounter = new int[length];
        RankName = new String[length];
        for (int index = 0; index < length; index++) {
            mRankQueue[index] = new ArrayList<>();
            mUserQueue[index] = new ArrayList<>();
            mWorksQueue[index] = new ArrayList<>();
        }
        NowName = "信息";
        NowTick = System.currentTimeMillis();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
//                sleepWaitting(2000);
                Object object = MAPI.READ_OBJECT_FILE(MDBS.getRankCounterPath());
                if (object instanceof int[]){
                    mRankCounter = (int[])object;
                }
                while (!isClose && !MAPP.threadStop) {               // 还没有下载成功mKcAGiftBean 会提示 后台忙，请稍候再试
                    readGiftRank();
                    if (MAPP.mKcAGiftBean != null){                  // 下载成功mKcAGiftBean
                        break;
                    }
                }
                NowName = "开始";
                NowTick = System.currentTimeMillis();
                while (!isClose && !MAPP.threadStop){
                    int number = getNextNumber();
                    if (number >= 0){
                        findWorks(number, MAPP.mWorksType[number]);
                    }else {
                        sleepWaitting(2000);
                    }
                }
            }
        }).start();
    }
    private static int getNextNumber(){
        if (!isPause && MAPP.mTaskEach != null && mRankQueue != null && mUserQueue != null) {      // 在评论之中找到的用户队列)
            int number = gNumber;
            synchronized (MAPP.mLockTask) {
                if (++gNumber < MAPP.mTaskEach.length) {
                    if (MAPP.mTaskEach[number].length > 1){
                        return number;
                    }
                    return number;
                }else {
                    gNumber = 0;
                }
            }
        }
        return -1;
    }
//                        MLOG(String.format("QueueA isPause %s", isPause));
//                boolean allApp32 = true;                        // App32的各种作品之中，只要有一种还没有找到作品，就先不做其他的App的
//                for (int number = 0; number < MAPP.mTaskEach.length; number++) {              // 先将所有记录运行
//                    if (MAPP.mTaskEach[number].length > 1 && MAPP.mWorksType[number] < 32) {
//                        if (!isPause) {
//                            if (!findWorks(number, MAPP.mWorksType[number])) {
////                                        MLOG(String.format("QueueA findWorksA %s %s %s %s", MAPP.mWorksType[number], mWorksQueue[number].size(), mUserQueue[number].size(), mRankQueue[number].size()));
//                                allApp32 = false;
//                            }
//                        }
//                    }
//                }
//                if (allApp32) {                                                  // App32的各种作品之中，只要有一种还没有找到作品，就先不做其他的App的
//                    for (int number = 0; number < MAPP.mTaskEach.length; number++) {              // 先将所有记录运行
//                        if (MAPP.mTaskEach[number].length > 1 && MAPP.mWorksType[number] > 32) {
//                            findWorks(number, MAPP.mWorksType[number]);
//                        }
//                    }
//                }

    public static void setClose(){
        isClose = true;
        breakWaitting();
    }
    public static void setPause(boolean pause){
        isPause = pause;
        breakWaitting();
    }
    public static void setApp33(TaskEach[] taskEach){
        MAPP.lockWrite33("setApp33");
        if (taskEach != null && taskEach.length > 1){           // 在列表前面加一个空的任务用于总状态显示及增加任务
            int length = taskEach.length - 1;
//            MLOG(String.format("QueueA setApp33B %s", length));
            mAccount33 = new String[length][2];
            for (int index = 0; index < length; index++){
                App33.setUser(taskEach[1 + index].mBDbsAccount);
                mAccount33[index][0] = App33.gsUserID;
                mAccount33[index][1] = App33.gsToken;
            }
        }
        MAPP.lockWrite33(null);
    }

    public static boolean getWorksQueue(int worksType, List<BFileBase> worksList, List<BFileBase> blackList, String city){
        if (mWorksQueue != null && MAPP.mWorksType != null) {
            for (int number = 0; number < MAPP.mWorksType.length; number++){
                if (worksType == MAPP.mWorksType[number]){
                    Random random = new Random();
                    int flag = random.nextInt();
                    int counter = 0;
                    if (mWorksQueue[number] != null && mWorksQueue[number].size() > 0) {
                        synchronized (mWorksQueue[number]) {
//                            MLOG(String.format("QueueA getWorksQueueA %s(%s)", worksType, mWorksQueue[number].size()));
                            while (true) {
                                if (counter >= mWorksQueue[number].size()) {
                                    break;
                                }
                                BFileBase bFileBase = mWorksQueue[number].get(counter);
                                if (RunUtils.sameBFileBase(bFileBase, blackList)){     // 相同的 不能评论的用户/已经评论过的用户作品
                                    ++counter;
                                    continue;
                                }

                                if ((flag & 1) != 0) {
                                    worksList.add(bFileBase);
//                                    MLOG(String.format("QueueA findWorksB D %s %s_%s %s", worksType, bFileBase.UserIdS, bFileBase.WorksIdS, bFileBase.RankName));
                                    mWorksQueue[number].remove(counter);
                                } else {
                                    ++counter;
                                }
                                flag >>= 1;
                                if (flag == 0) {
                                    break;
                                }
                            }
//                            MLOG(String.format("QueueA getWorksQueueB %s(%s)", worksType, mWorksQueue[number].size()));
                        }
                        return true;
                    }
                }
            }
        }
        return false;
    }
    private static boolean findWorks(int number, byte worksType){
        long tick = System.currentTimeMillis();
        NowTick = tick;                                             // 在占用中的作品时间
        if (mWorksQueue[number].size() < 100){
            if (mRankQueue[number].size() < 3) {                         // 榜单队列很少了
                NowName = String.format("%sA", MAPP.mWorksName[worksType]);                      // 在占用中的作品类型
                getRankWorks(number, worksType);                                    // 从榜单找用户及作品
//            MLOG(String.format("QueueA findWorksA %s(%s)", worksType, mRankQueue[number].size()));
            }
            BFileBase bFileBase;
            if (mRankQueue[number].size() != 0 && mUserQueue[number].size() == 0) {            // 榜单队列已经有的而且用户队列还没有开始
                bFileBase = mRankQueue[number].get(0);          // 从榜单队列取出来一个
                mRankQueue[number].remove(0);            // 从榜单队列移除一个
                RankName[number] = bFileBase.RankName;
//            MLOG(String.format("QueueA findWorksB %s %s_%s %s", worksType, bFileBase.UserIdS, bFileBase.WorksIdS, bFileBase.RankName));
                NowName = String.format("%sB", MAPP.mWorksName[worksType]);                      // 在占用中的作品类型
                getWorksInfo(number, worksType, bFileBase);
            }else if (mUserQueue[number].size() != 0) {            // 有用户队列
                NowName = String.format("%sC", MAPP.mWorksName[worksType]);                      // 在占用中的作品类型
//                MLOG(String.format("QueueA findWorksC %s %s", worksType, mUserQueue[number].size()));
                for (int counter = 32; counter != 0; counter--) {
                    bFileBase = mUserQueue[number].get(0);        // 从用户队列取出来一个
                    mUserQueue[number].remove(0);          // 从作品移除一个
                    bFileBase.RankName = RankName[number];
//                    MLOG(String.format("QueueA findWorksC %s %s_%s %s", worksType, bFileBase.UserIdS, bFileBase.WorksIdS, bFileBase.RankName));
                    getWorksInfo(number, worksType, bFileBase);
                    if (mUserQueue[number].size() == 0) {
                        break;
                    }
                }
//                MLOG(String.format("QueueA findWorksD %s %s", worksType, mUserQueue[number].size()));
            }
        }
        if (mWorksQueue[number].size() == 0){                   // App32的各种作品之中，只要有一种还没有找到作品，就先不做其他的App的
            NowName = String.format("%sE", MAPP.mWorksName[worksType]);
            return false;
        }
        return true;
    }



    private static boolean getWorksInfo(int number, byte worksType, BFileBase bFileBase){            // 输入BFileBase读取作品的详细信息及评论列表加入到mUserQueue列表之中
        BAppUser bAppUser = null;
        String filePath = MDBS.getUserPath(worksType, bFileBase.UserIdS);
        if (MAPI.IS_EXIST_FILE(filePath)) {                 // 本地数据库存在
            bAppUser = MDBS.getBAppUser(worksType, bFileBase.UserIdS);
        } else {
            if (worksType < 32) {
                if (waitWriteLock(worksType, String.format("%s_用户", MAPP.mWorksName[worksType]))) {
                    bAppUser = App32.getUserInfo(bFileBase.UserIdS);
                    clearWriteLock(worksType);
                }
            }else if (worksType == 33) {
                if (MAPP.mBLock33.Text == null) {                       // 只有写入空闲才使用网络动作
                    app33SsetUser();
                    bAppUser = App33.getUserInfo(bFileBase.UserIdS);
                }
            }
            if (bAppUser != null) {
                MDBS.setBAppUser(bAppUser);
            }
        }
        if (bAppUser == null){
//            MLOG(String.format("QueueA getWorksInfo Exit"));
            return false;
        }
//        MLOG(String.format("QueueA getWorksInfoB %s %s", worksType, bFileBase.WorksIdS));
        if (bFileBase.WorksIdS == null) {                    // 没有作品
            BWorksList bWorksList = MDBS.getWorksList(worksType, bFileBase.UserIdS);       // 先看看数据库有没有
            if (bWorksList == null) {
                bWorksList = new BWorksList();
            }
            if (bWorksList.WorksIdS == null) {
                if (worksType < 32) {
                    if (waitWriteLock(worksType, String.format("%s_作品列表", MAPP.mWorksName[worksType]))) {
                        bWorksList.WorksIdS = App32.getWorksList(worksType, bFileBase.UserIdS, false);
                        clearWriteLock(worksType);
                    }
//                    MLOG(String.format("QueueA getWorksInfoA %s %s %s", worksType, bFileBase.UserIdS, bWorksList.WorksIdS != null ? bWorksList.WorksIdS.length : 0));
                } else if (worksType == 33) {
                    if (MAPP.mBLock33.Text == null) {                       // 只有写入空闲才使用网络动作
                        app33SsetUser();
                        bWorksList.WorksIdS = App33.getWorksList(bFileBase.UserIdS, false);    // 实际找
                    }
                }
            }
            if (bWorksList.WorksIdS != null) {
                for (int index = 0; index < bWorksList.WorksIdS.length; index++) {
                    int counter = (bWorksList.Counter++) % bWorksList.WorksIdS.length;
                    bFileBase.WorksIdS = bWorksList.WorksIdS[counter];
                    if (getBAppWorks(worksType, bFileBase) != null) {
                        synchronized (mWorksQueue[number]) {
                            if (!RunUtils.sameBFileBase(bFileBase, mWorksQueue[number])) {
                                mWorksQueue[number].add(bFileBase);
                                RunUtils.addBFileBase(bFileBase, mWorksQueue[number]);
                                break;
                            }
                        }
                    }
                }
                MDBS.setWorksList(worksType, bFileBase.UserIdS, null, bWorksList);
            }
        }else {
            if (getBAppWorks(worksType, bFileBase) != null) {
                synchronized (mWorksQueue[number]) {
//                MLOG(String.format("QueueA getWorksInfo Q %s %s %s %s", worksType, bFileBase.UserIdS, bFileBase.WorksIdS, bFileBase.RankName));
                    RunUtils.addBFileBase(bFileBase, mWorksQueue[number]);
                }
            }
        }
//        MLOG(String.format("QueueA getWorksInfo D %s %s %s %s", worksType, bFileBase.UserIdS, bFileBase.WorksIdS, bFileBase.RankName));
        if (bFileBase.WorksIdS == null){
//            MLOG(String.format("QueueA getWorksInfo Exit"));
            return false;
        }
        BAppWorks bAppWorks =getBAppWorks(worksType, bFileBase);// MDBS.getBAppWorks(worksType, bFileBase.UserIdS, bFileBase.WorksIdS);      // 先看看数据库有没有
        if (bAppWorks == null) {
//            MLOG(String.format("QueueA getWorksInfo Exit"));
            return false;
        }
        long tick1 = System.currentTimeMillis();
        long tick2 = tick1;
//        MLOG(String.format("QueueA RunE 6 %s(%s)%s", worksType, bFileBase.UserIdS, bFileBase.WorksIdS));
        BCommentInfo[] bCommentInfos = MDBS.getBCommentList(worksType, bFileBase.UserIdS, bFileBase.WorksIdS);
//        MLOG(String.format("QueueA getWorksInfoD %s %s", worksType, bCommentInfos));
        if (bCommentInfos == null) {
            if (worksType < 32) {
                if (waitWriteLock(worksType, String.format("%s_评论列表", MAPP.mWorksName[worksType]))) {
                    bCommentInfos = App32.getCommentList(bFileBase.UserIdS, bFileBase.WorksIdS, "0", 100);
                    clearWriteLock(worksType);
                }
                if (bCommentInfos != null) {
                    MDBS.setBCommentList(worksType, bFileBase.UserIdS, bFileBase.WorksIdS, bCommentInfos);
                }
            }else if (worksType == 33) {
                if (MAPP.mBLock33.Text == null) {                       // 只有写入空闲才使用网络动作
                    app33SsetUser();
                    bCommentInfos = App33.getCommentList(0, bFileBase.UserIdS, bFileBase.WorksIdS, null);
                }
            }
        }
//        MLOG(String.format("QueueA getWorksInfoE %s %s", worksType, bCommentInfos));
        if (bCommentInfos != null) {
            BFileBase[] bFileBases = new BFileBase[bCommentInfos.length];
            for (int index = 0; index < bFileBases.length; index++) {
                bFileBases[index] = new BFileBase();
                bFileBases[index].UserIdS = bCommentInfos[index].CommenterIdS;
//                MLOG(String.format("QueueA getCommentListA C %s", bFileBases[index].UserIdS ));
            }
            RunUtils.addBFileBase(bFileBases, mUserQueue[number], null);
//            MLOG(String.format("QueueA getWorksInfo K %s %s %s %s", worksType, bFileBase.RankName, bFileBases.length, mUserQueue[number].size()));
        }
        return true;
    }
    public static BAppWorks getBAppWorks(byte worksType, BFileBase bFileBase){
        BAppWorks bAppWorks = MDBS.getBAppWorks(worksType, bFileBase.UserIdS, bFileBase.WorksIdS);      // 先看看数据库有没有
//        MLOG(String.format("QueueA getWorksInfoC %s %s", worksType, bAppWorks));
        if (bAppWorks == null) {
            if (worksType < 32) {
                if (waitWriteLock(worksType, String.format("%s_作品", MAPP.mWorksName[worksType]))) {
                    bAppWorks = App32.getWorksInfo(bFileBase.UserIdS, bFileBase.WorksIdS);
                    clearWriteLock(worksType);
                }
//                MLOG(String.format("QueueA RunE 3 %s(%s)%s", worksType, bFileBase.UserIdS, bFileBase.WorksIdS));
            } else if (worksType == 33) {
                if (MAPP.mBLock33.Text == null) {                       // 只有写入空闲才使用网络动作
                    app33SsetUser();
                    bAppWorks = App33.getWorksInfo(bFileBase.UserIdS, bFileBase.WorksIdS);
                }
            }
            if (bAppWorks != null) {                            // 实际读取回来
//                MLOG(String.format("findWorksA BAppUser RunE 5 %s(%s)%s", worksType, bFileBase.UserIdS, bFileBase.WorksIdS));
                MDBS.setBAppWorks(bAppWorks);
//                String filePath = MDBS.getWorksPath(bAppWorks.WorksType, bFileBase.UserIdS, bFileBase.WorksIdS);
//                MLOG(String.format("findWorksA BAppUser RunE 6 %s(%s)%s", worksType, MAPI.GET_FILE_LENGTH(filePath), filePath));
            }
        }
        return bAppWorks;
    }

    private static void getRankWorks(int number, byte worksType){                                // 从榜单找用户及作品
        BFileBase[] bFileBases = null;
        int index = 0;

//        int length = mRankQueue[number].size();                // 原来的长度
        int step = mRankCounter[number]++;
        String rankName = null;
        MAPI.WRITE_OBJECT_FILE(MDBS.getRankCounterPath(), mRankCounter);     // 保存mRankCounter
        if (worksType < 32) {
//            MLOG(String.format("QueueA getRankWorks %s(%s)%s", worksType, MAPP.mBLock32.Text, MAPP.mKcBRankInfo));
            if (MAPP.mBLock32.Text == null) {                       // 只有写入空闲才使用网络动作
                if (MAPP.mKcBRankInfo != null) {
                    index = Math.abs(step % MAPP.mKcBRankInfo.length);
                    AUserBase aUserBase = new AUserBase();
                    aUserBase.UserID = MAPP.mKcBRankInfo[index].UserID;
                    rankName = MAPP.mKcBRankInfo[index].Name;
                    if (waitWriteLock(worksType, String.format("%s_%s", MAPP.mWorksName[worksType], rankName))) {
                        bFileBases = App32.getRankList(worksType, aUserBase, 1000);
                        clearWriteLock(worksType);
                    }
//                    MLOG(String.format("QueueA getRankList %s %s", worksType, bFileBases!=null?bFileBases.length:0));
                }
            }
        } else if (worksType == 33) {
            if (MAPP.mBLock33.Text == null) {                       // 只有写入空闲才使用网络动作
                app33SsetUser();
                index = step % MAPP.tabRankChangBa.length;
                rankName = MAPP.tabRankChangBa[index];
                bFileBases = App33.getRankList(rankName);
            }
        }
        if (bFileBases != null) {
            for (int counter = 0; counter < bFileBases.length; counter++) {
                bFileBases[counter].RankName = rankName;
//                MLOG(String.format("QueueA getRankWorksA %s %s_%s %s", worksType, bFileBases[counter].UserIdS, bFileBases[counter].WorksIdS, bFileBases[counter].RankName));
            }
            RunUtils.addBFileBase(bFileBases, mRankQueue[number], null);
        }
//        MLOG(String.format("QueueA getRankWorks 从%s(%s)榜找到作品：%s(%s) %s", worksType, rankArea, mRankQueue[number].size() - length, mRankQueue[number].size(), mRankCounter[number]));
    }

    private static void app33SsetUser(){
        if (mAccount33 != null) {
            int counter = gApp32Count++ % mAccount33.length;
            App33.setUser(mAccount33[counter][0], mAccount33[counter][1]);
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    private static void readGiftRank(){
        EditUtils editUtils = new EditUtils();
        List<AFileBase> giftIcon = null;
        if (MAPP.mKcAGiftBean == null){
            List<AGiftBean> aGiftBeans = (List)MDBS.getRankGiftList(true);
            if (aGiftBeans != null){
                MAPP.mKcAGiftBean = aGiftBeans.toArray(new AGiftBean[aGiftBeans.size()]);
                editUtils.logAGiftBean();
            }else {
                giftIcon = new ArrayList<>();
            }
        }
        List<AFileBase> rankArea = null;
        if (MAPP.mKcBRankInfo == null){
            List<BRankInfo> bRankInfos = (List)MDBS.getRankGiftList(false);
//            MLOG(String.format("QueueA readGiftRank getBRankInfo %s %s", bRankInfos != null?bRankInfos.size():0, MDBS.getRankGiftList(false)));
            if (bRankInfos != null){
                MAPP.mKcBRankInfo = bRankInfos.toArray(new BRankInfo[bRankInfos.size()]);
                editUtils.logBRankInfo();
            }else {
                rankArea = new ArrayList<>();
            }
        }
        String loginFlag = MSKIN.getMemoryString(W.ManageLoginFlag, false);
        boolean result = false;
        MLOG("QueueA readGiftRank AA "+loginFlag);
        while (!MAPP.threadStop) {
            if (waitWriteLock(0, "管理员_礼物")){
//                MLOG("QueueA readGiftRank BB ");
                App32.setUser(loginFlag, (byte) 0);
                result = App32.getGiftAndRank(giftIcon, rankArea);
                clearWriteLock(0);
                break;
            }
            sleepWaitting(100);
        }
        MAPP.gErrorManage = App32.getLastError();
        MLOG("QueueA readGiftRank CC MAPP.gErrorManage "+MAPP.gErrorManage);
        if (result) {
//            MLOG("QueueA readGiftRank B ");
            if (MAPP.mKcAGiftBean == null && giftIcon != null){
                editUtils.makeGiftBean(giftIcon);
                editUtils.logAGiftBean();
            }
            if (MAPP.mKcBRankInfo == null && rankArea.size() > 0){
                editUtils.makeBRankInfo(rankArea);
                editUtils.logBRankInfo();
            }
        }
//        if (waitWriteLock(0, "管理员_榜单")) {
//            if (!App32.getGiftAndRank(giftIcon, rankArea)) {
//                if (MAPP.gManageLogin == 0) {
//                    MAPP.gManageLogin = 1;
//                }
//                MLOGE(String.format("QueueA getGiftAndRank 没有成功 %s %s", MAPP.gManageLogin, MSKIN.getMemoryString(W.ManageLoginFlag)));
//            }
//            clearWriteLock(0);
//        }
    }
    public static synchronized String setKgAppDbs(BDbsAccount bDbsAccount, int svrType){
        String result;
        String key = getKgAppDbsKey(bDbsAccount, svrType);          // 从管理员账号及输入的账号生成上传的key
        if (key != null) {
            CApiUtils cApiUtils = new CApiUtils();
            String richText = null;
            switch (svrType) {
                case MDBS.SVR_LOGIN:
//                    if (MAPI.isEmpty(bDbsAccount.UserIdS) || MAPI.isEmpty(bDbsAccount.LoginFlag)){
//                        MLOGE(String.format("KgAppDbsA 4 %s_%02x不能上传空的数据_%s_%s", bDbsAccount.AccountName, bDbsAccount.WorksType, bDbsAccount.UserIdS, bDbsAccount.LoginFlag));
//                        return "不能上传空的数据";
//                    }
                    richText = cApiUtils.encodeRichText(String.format("%s:%s:%s", bDbsAccount.LoginFlag, bDbsAccount.AccountName, bDbsAccount.UserName));
                    break;
                case MDBS.SVR_COMMENT:
                    richText = cApiUtils.encodeRichText(String.format("%s", bDbsAccount.TextComment[0]));
            }
            String text = getSvrText(bDbsAccount, svrType, key);
            if (text == null || !text.equals(richText)) {
                MLOG(String.format("KgAppDbsA 3 %02x(%s) key:%s(%s)", bDbsAccount.WorksType, svrType, key, richText));
                String sendText = String.format("%s,%s", key, richText);
                String loginFlag = MSKIN.getMemoryString(W.ManageLoginFlag, false);
                if (waitWriteLock(0, "管理员_上传")) {
//MLOGE(String.format("QueueA gWorksTypeEA %s", bDbsAccount.WorksType));
                    App32.setUser(loginFlag, (byte) 0);
                    result = App32.writeKgAppDbs(sendText);
                    clearWriteLock(0);
                    if ("ok".equals(result)) {
                        setSvrText(bDbsAccount, svrType, key, richText);
                        MLOG(String.format("KgAppDbsA 5 %s_%s_%08x上传成功：%s", bDbsAccount.AccountName, bDbsAccount.WorksType, bDbsAccount.CrcSum5, sendText));
                    } else {
                        if (result.indexOf("登录") >= 0){
                            if (MAPP.gManageLogin != 2) {
                                MAPP.gManageLogin = 1;
                            }
                        }
                        MLOGE(String.format("KgAppDbsA 7 %s上传出错：%s(%s)%s", bDbsAccount.AccountName, result, mMyUtils.getServerNumber(), loginFlag));
                    }
                    return result;
                }
            } else {
//                MLOG(String.format("KgAppDbsA8 %s %02x(%s)数据库相同，不需要重新上传", bDbsAccount.AccountName, bDbsAccount.WorksType, svrType));
            }
        }
        return "参数不正确";
    }
    public static synchronized String getKgAppDbsKey(BDbsAccount bDbsAccount, int svrType, boolean remote){
        String key = getKgAppDbsKey(bDbsAccount, svrType);
        if (key != null) {
            if (!remote){                                       // 从本地找相同的账号
                String text = getSvrText(bDbsAccount, svrType, key);
                MLOG(String.format("KgAppDbsA B %s_%02x(%s)%s", bDbsAccount.CrcSum5, svrType, key, text));
                return text;
            }
            String sendText = String.format("0,%s", key);
            if (waitWriteLock(0, "管理员_读取")) {
                App32.setUser(MSKIN.getMemoryString(W.ManageLoginFlag, false), (byte) 0);
                String result = App32.readKgAppDbs(sendText);
                clearWriteLock(0);
                if (result != null) {
                    String[] split = result.split(",");
                    if (split.length >= 6) {
                        String dataStr = split[6];//MAPI.GET_SPLIT_STRING(result, 6, ",");
                        CApiUtils cApiUtils = new CApiUtils();
                        return cApiUtils.decodeRichText(dataStr);
                    }
                }
            }
        }
        return null;
    }
    public static synchronized String getKgAppDbsKey(BDbsAccount bDbsAccount, int svrType){
        String accountName = null;
        long number = 0;
        if (MAPP.mManageAccount != null) {
            accountName = MAPP.mManageAccount.AccountName;
            if (accountName != null && accountName.length() >= 11) {                           // 必须为手机号码
                number = Long.parseLong(accountName);
                if (number > 100000000) {
                    int worksType = bDbsAccount.WorksType;
                    if ((svrType & MDBS.SVR_MIX) != 0) {
                        worksType = getWorksType(bDbsAccount.WorksType);
                    }
                    return String.format("%s,%s,%s,%s", svrType, number % 100000000, worksType, bDbsAccount.CrcSum5);
                }
            }
        }
        MLOGE(String.format("getKgAppDbsKey 账号出错：%s(%s)%s", accountName, number, MAPP.mManageAccount));
        return null;
    }

    public static void setSvrText(BDbsAccount bDbsAccount, int svrType, String key, String text){
        int worksType = bDbsAccount.WorksType;
        if ((svrType & MDBS.SVR_MIX) != 0){
            worksType = getWorksType(bDbsAccount.WorksType);
        }
        MDBS.setFreeText(bDbsAccount, worksType << 24 | svrType, key, text);
//        MDBS.setFreeText(bDbsAccount.CrcSum5, worksType, svrType, key, text);
    }
    public static String getSvrText(BDbsAccount bDbsAccount, int svrType, String key){
        int worksType = bDbsAccount.WorksType;
        if ((svrType & MDBS.SVR_MIX) != 0){
            worksType = getWorksType(bDbsAccount.WorksType);
        }
        return MDBS.getFreeText(bDbsAccount, worksType << 24 | svrType, key);
//        return MDBS.getFreeText(bDbsAccount.CrcSum5, worksType, svrType, key);
    }
    public static int getWorksType(int worksType){
        if (worksType < 32) {                    //
            return 32;
        }
        if (worksType == 49) {                    //
            return  33;
        }
        return worksType;
    }
    private static boolean waitWriteLock(int worksType, String text){
        while (!isClose && !MAPP.threadStop){
            if (worksType < 32) {
                if (MAPP.lockWrite32(text)) {
                    return true;
                }
            }else if (worksType == 33) {
                if (MAPP.lockWrite33(text)) {
                    return true;
                }
            }
            sleepWaitting(100);
        }
        return false;
    }
    private static void clearWriteLock(int worksType){
        if (worksType < 32) {
            MAPP.lockWrite32(null);
        }else if (worksType == 33) {
            MAPP.lockWrite33(null);
        }
    }

    private static void breakWaitting(){                                    // 退出任何等待
        if (mRankQueue != null) {
            synchronized (mRankQueue) {                             // 借用对象锁
                mRankQueue.notifyAll();
            }
        }
    }
    private static void sleepWaitting(int millisecond){                     // 等待毫秒
        synchronized (mRankQueue) {                                 // 借用对象锁
            try {
                mRankQueue.wait(millisecond);                       // 等待信号
            } catch (Exception e) {
            }
        }
    }
}
